package edu.hm.activebadge.rfid.adaption.server;


import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import java.awt.GridLayout;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;

import javax.swing.ImageIcon;

import javax.swing.JScrollPane;

import edu.hm.activebadge.rfid.acquisition.badge.BadgeParameter;
import edu.hm.activebadge.rfid.adaption.IAdaption;
import edu.hm.activebadge.rfid.adaption.Worker;
import edu.hm.activebadge.rfid.interpretation.InterpretationLogik;
import edu.hm.activebadge.rfid.representation.ContextObject;

public class ServerFrontend extends JFrame implements ActionListener, TableModelListener {

	private JPanel contentPane;
	private JTextField textArea;
	private JButton btnFindbadge;
	private JButton btnWithbadge;
	private JButton btnLooktag;
	private JButton btnNotifybadge;
	private JTextField withText;
	private JTextField lookText;
	private JTextField notifyText;
	private JTextField findText;
	private JButton btnProgrammBeenden;
	
	private InterpretationLogik serverLogik;
	private Thread logikThread;
	
	private DefaultTableModel personModel;
	private DefaultTableModel itemModel;
	private JScrollPane scrollPane;
	private JTable personTable;
	
	private String notifyWhen;
	private boolean notify = false;
	
	IAdaption workmachine;
	private JScrollPane scrollPane_1;
	private JTable itemTable;
	private JButton btnEmergencyperson;
	private JTextField emergencyTxt;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ServerFrontend frame = new ServerFrontend();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ServerFrontend() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(ServerFrontend.class.getResource("/Icons/icons/monitor.png")));
		setTitle("Active Badge Server");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 800, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new GridLayout(2, 2, 10, 10));
		
		
		//JTable
		String[] columnNames = {"Person", "Location", "Timestamp"};
		personModel = new DefaultTableModel(columnNames, 0){ 
	        public boolean isCellEditable(int row, int column) { 
	            return false; 
	        }};
	    personModel.addTableModelListener(this);
		
		scrollPane = new JScrollPane();
		contentPane.add(scrollPane);
		
		personTable = new JTable(personModel);
		personTable.setRowSelectionAllowed(false);
		scrollPane.setViewportView(personTable);
		
		scrollPane_1 = new JScrollPane();
		contentPane.add(scrollPane_1);
		
		String[] columnNames2 = {"Item", "Location", "Timestamp"};
		itemModel = new DefaultTableModel(columnNames2, 0){ 
	        public boolean isCellEditable(int row, int column) { 
	            return false; 
	        }};
	    itemModel.addTableModelListener(this);
		
		itemTable = new JTable(itemModel);
		scrollPane_1.setViewportView(itemTable);
		
		JPanel panel = new JPanel();
		contentPane.add(panel);
		panel.setLayout(new GridLayout(6, 2, 10, 10));
		
		btnWithbadge = new JButton("With(Badge):");
		btnWithbadge.setActionCommand("with");
		btnWithbadge.setIcon(new ImageIcon(ServerFrontend.class.getResource("/Icons/icons/group.png")));
		btnWithbadge.addActionListener(this);
		panel.add(btnWithbadge);
		
		withText = new JTextField();
		panel.add(withText);
		withText.setColumns(10);
		
		btnLooktag = new JButton("Look(Tag):");
		btnLooktag.setActionCommand("look");
		btnLooktag.setIcon(new ImageIcon(ServerFrontend.class.getResource("/Icons/icons/tag_blue.png")));
		btnLooktag.addActionListener(this);
		panel.add(btnLooktag);
		
		lookText = new JTextField();
		panel.add(lookText);
		lookText.setColumns(10);
		
		btnNotifybadge = new JButton("Notify(Badge):");
		btnNotifybadge.setActionCommand("notify");
		btnNotifybadge.setIcon(new ImageIcon(ServerFrontend.class.getResource("/Icons/icons/bell.png")));
		btnNotifybadge.addActionListener(this);
		panel.add(btnNotifybadge);
		
		notifyText = new JTextField();
		panel.add(notifyText);
		notifyText.setColumns(10);
		
		btnFindbadge = new JButton("Find(Badge):");
		btnFindbadge.setActionCommand("find");
		btnFindbadge.setIcon(new ImageIcon(ServerFrontend.class.getResource("/Icons/icons/zoom.png")));
		btnFindbadge.addActionListener(this);
		panel.add(btnFindbadge);
		
		findText = new JTextField();
		findText.setText("");
		panel.add(findText);
		findText.setColumns(10);
		
		btnProgrammBeenden = new JButton("Programm beenden");
		btnProgrammBeenden.setIcon(new ImageIcon(ServerFrontend.class.getResource("/Icons/icons/application_delete.png")));
		btnProgrammBeenden.setActionCommand("end");
		btnProgrammBeenden.addActionListener(this);
		
		btnEmergencyperson = new JButton("Emergency(Person):");
		btnEmergencyperson.setIcon(new ImageIcon(ServerFrontend.class.getResource("/Icons/icons/group_error.png")));
		btnEmergencyperson.setActionCommand("emergency");
		btnEmergencyperson.addActionListener(this);
		panel.add(btnEmergencyperson);
		
		emergencyTxt = new JTextField();
		panel.add(emergencyTxt);
		emergencyTxt.setColumns(10);
		panel.add(btnProgrammBeenden);
		
		textArea = new JTextField();
		contentPane.add(textArea);
		textArea.setColumns(10);
		
		
		workmachine = new Worker(personModel, itemModel, textArea);
		
		//Starten der Logik MIT THREAD!
		try {
			serverLogik = new InterpretationLogik(workmachine);
			logikThread = new Thread(serverLogik);
			logikThread.start();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	public void updateTable(IContextRepresentation context){
		
		int rowCount = 0;
		while (rowCount < personModel.getRowCount()){
			if(context.getBadge().equals(personModel.getValueAt(rowCount, 0))){
				personModel.setValueAt(context.getTag(), rowCount, 1);
				personModel.setValueAt(context.getTimestamp().get(Calendar.DAY_OF_MONTH)+"."+context.getTimestamp().get(Calendar.MONTH)+"."+context.getTimestamp().get(Calendar.YEAR)+" um "+context.getTimestamp().get(Calendar.HOUR_OF_DAY)+":"+context.getTimestamp().get(Calendar.MINUTE)+":"+context.getTimestamp().get(Calendar.SECOND), rowCount, 2);
				break;
			}			
			rowCount++;
		}
		
		if(rowCount==personModel.getRowCount()){
			String[] row = {context.getBadge(), context.getTag(), context.getTimestamp().get(Calendar.DAY_OF_MONTH)+"."+context.getTimestamp().get(Calendar.MONTH)+"."+context.getTimestamp().get(Calendar.YEAR)+" um "+context.getTimestamp().get(Calendar.HOUR_OF_DAY)+":"+context.getTimestamp().get(Calendar.MINUTE)+":"+context.getTimestamp().get(Calendar.SECOND)};
			personModel.addRow(row);
		}
		
	}*/

	@Override
	public void actionPerformed(ActionEvent e) {
		
		if(e.getActionCommand().equals("find")){
			int row = 0;
			while(row<personModel.getRowCount()){
				if(personModel.getValueAt(row, 0).equals(findText.getText()))
				{
					textArea.setText(personModel.getValueAt(row, 0)+" last known location is "+ personModel.getValueAt(row, 1)+". Located at "+personModel.getValueAt(row, 2));
					break;
				}
				row++;}
				
			if(row==personModel.getRowCount())
				textArea.setText(findText.getText()+"can't be found.");
			

		}
		if(e.getActionCommand().equals("look")){
			int row = 0;
			String mitarbeiter = "\n";
			while(row<personModel.getRowCount()){
				if(personModel.getValueAt(row, 1).equals(lookText.getText()))
				{
					mitarbeiter= mitarbeiter + personModel.getValueAt(row, 0)+"\n";
				}
				row++;
			}
				
			if(mitarbeiter.equals("\n"))
				textArea.setText("No one is at "+lookText.getText()+" or "+lookText.getText()+" isn't a location.");
			else
				textArea.setText("At "+lookText.getText()+" is/are following badge/s: "+mitarbeiter);

		}
		if(e.getActionCommand().equals("notify")){
			notify = true;
			notifyWhen= notifyText.getText();
			notifyText.setText("");
			textArea.setText("You will be notified if "+notifyWhen+" has been spotted.");
		}
		if(e.getActionCommand().equals("with")){
			//Badge finden
			int row = 0;
			String location ="";
			String mitarbeiter="";
			while(row<personModel.getRowCount()){
				if(personModel.getValueAt(row, 0).equals(withText.getText()))
				{
					location = (String) personModel.getValueAt(row, 1);
					break;
				}
				row++;
			}
			
			row=0;
			
			if(location=="")
				textArea.setText(findText.getText()+"can't be found.");
			else
			{
				while(row<personModel.getRowCount()){
					if(personModel.getValueAt(row, 1).equals(location)&&!personModel.getValueAt(row, 0).equals(withText.getText())){
						mitarbeiter= mitarbeiter + personModel.getValueAt(row, 0);
					}
					row++;
				}
			}
			
			if(mitarbeiter.equals(""))
				textArea.setText("No one else is at "+location);
			else
				textArea.setText("At the location "+location+" are probably following additional Badges:"+mitarbeiter);
		}
		if(e.getActionCommand().equals("end")){
			System.exit(0);
		}
		if(e.getActionCommand().equals("emergency")){
			Socket s;
			try {

				String location = new String();
				int rowCount = 0;
				while (rowCount < personModel.getRowCount()){
					if(emergencyTxt.getText().equals(personModel.getValueAt(rowCount, 0))){
						location = (String) personModel.getValueAt(rowCount, 1);
						break;
					}			
					rowCount++;
				}
				
				if(rowCount==personModel.getRowCount()){
					textArea.setText(emergencyTxt.getText()+" kann nicht gefunden werden.");
				}
				else
				{
					s = new Socket(ServerParameter.getClient(), Integer.parseInt(ServerParameter.getAlarmPort()));
					OutputStream os = s.getOutputStream();  
					ObjectOutputStream oos = new ObjectOutputStream(os);		
					oos.writeObject(new AlarmMessage(emergencyTxt.getText(), location, true));   
					oos.close();  
					os.close();  
					s.close(); 
					((Worker) workmachine).activateAlarm(emergencyTxt.getText());
				}

			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			} catch (UnknownHostException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}  
		}
	}

	@Override
	public void tableChanged(TableModelEvent e) {
		if(notify){
			if(notifyWhen.equals(personModel.getValueAt(e.getFirstRow(), 0))){
				textArea.setText(notifyWhen+" has been detected at location "+personModel.getValueAt(e.getFirstRow(), 1));
				//Ton
				Toolkit.getDefaultToolkit().beep();
				notify=false;
			}
		}
		
	}

}
